#import "YQPIntegerPayView.h"

#import "YQOrderManageListVC.h"

#import "YQOrderLogisticsWriteVC.h"
#import "YQGoodsOrderModel.h"
#import <AlipaySDK/AlipaySDK.h>
#import "OrderEvaViewController.h"
#import "YQPCartListModel.h"
#import "MYShopSalesOrderVC.h"
#import "MYNewsShopDetailsHotelVC.h"
#import "MYNewsShopDetailsScenicspotVC.h"
#import "MYNewsShopDetailsActionVC.h"
#import "YQGoodsActionOrderDetailsVC.h"
#import "YQGoodsScenicspotOrderDetailsVC.h"
#import "YQGoodsHotelOrderDetailsVC.h"
//#import "MYShopSalesOrderPayView.h"
#import "YQGoodsOrderDetailsVC.h"
#import <WXApi.h>

#import "YQPOrderLogicsViewController.h"

#import "YQQueryOrderEvaViewController.h"

@interface YQOrderManageListVC ()<YQOrderManageBtnActionCellDelegate>
@property (nonatomic,retain) NSMutableDictionary *payParameters;
@property (nonatomic,retain) NSTimer *timer;
@end

@implementation YQOrderManageListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySucceedAction) name:YJPaySucceedNotiKey object:nil];
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)setupView {
    [super setupView];
    self.listTableView.backgroundColor = kAPPTABLEVIEW_BG_COLOR;
    self.listTableView.frame = CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea-44);
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManageStateCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManageGoodsCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManagePriceCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManageBtnActionCell")
    [self setupRefresh:self.listTableView];
    [self onStartRefresh];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getOrderList];
}

-(void)onStartRefresh {
    self.page = 1;
    [self getOrderList];
}

- (void)onStartLoadMore {
    self.page ++ ;
    [self getOrderList];
}

-(void)getOrderList {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"limit"] = @"10";
    parameters[@"orderStatus"] = @(self.type);
    parameters[@"page"] = @(self.page); 
    
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendPostRequest:kPOST_QUERY_ORDER_LIST_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        [self stopRefresh];
        if (responseObject.code == 0) {
            if (self.page == 1) {
                [self.dataArr removeAllObjects];
            }
            NSArray *arr = [NSArray modelArrayWithClass:YQGoodsOrderModel.class json:responseObject.data[@"list"]];
            [self.dataArr addObjectsFromArray:arr];
            [self.listTableView reloadData];
            
            if (arr.count < 10) {
                [self.listTableView.mj_footer endRefreshingWithNoMoreData];
            }
            
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
        
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
//        YQUITIPSERROR(error);
        [self stopRefresh];
    }];
    
}

#pragma mark - JXCategoryListContentViewDelegate

- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.listTableView;
}
#pragma mark - JXCategoryListContentViewDelegate end

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    YQGoodsOrderModel *ordermOrder = nil;
    if (section < self.dataArr.count) {
        ordermOrder = self.dataArr[section];
    }
    if (ordermOrder.orderStatus == 201) {
        return 2 + ordermOrder.orderItemList.count;
    }
    return 3 + ordermOrder.orderItemList.count;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    YQGoodsOrderModel *ordermOrderModel = nil;
    if (indexPath.section < self.dataArr.count) {
        ordermOrderModel = self.dataArr[indexPath.section];
    }
    if (indexPath.row == 0) {
        YQOrderManageStateCell *stateCell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManageStateCell"];
        //stateCell.stateLb.text = @"等待买家付款";
        stateCell.orderStatus = ordermOrderModel.orderStatus;
        return stateCell;
    }else if (indexPath.row == 1+ordermOrderModel.orderItemList.count) {
        YQOrderManagePriceCell *priceCell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManagePriceCell"];
        
        priceCell.goodsOrdreModel = ordermOrderModel;
        return priceCell;
    }else if (indexPath.row == 2 + ordermOrderModel.orderItemList.count){
        YQOrderManageBtnActionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManageBtnActionCell"];
        cell.indexPath = indexPath;
        cell.delegate = self;
//        [cell.leftBtn setTitle:@"取消订单" forState:(UIControlStateNormal)];
        cell.goodsOrdreModel = ordermOrderModel;
        return cell;
    }else{
        YQGoodsOrderItemModel *itemModel = nil;
        if (indexPath.row - 1 < ordermOrderModel.orderItemList.count) {
            itemModel = ordermOrderModel.orderItemList[indexPath.row -1];
        }
        YQOrderManageGoodsCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManageGoodsCell"];
        goodsCell.goodsModel = itemModel;
        goodsCell.refundBtn.hidden = YES;
        return goodsCell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YQGoodsOrderModel *ordermOrder = nil;
    if (indexPath.section < self.dataArr.count) {
        ordermOrder = self.dataArr[indexPath.section];
    }
    
    if (indexPath.row == 0) {
        return 47;
    }else if (indexPath.row == 1 + ordermOrder.orderItemList.count) {
        return 32;
        
    }else if(indexPath.row == 2 + ordermOrder.orderItemList.count) {
        return 52;
    }
    return 104;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YQGoodsOrderModel *ordermOrderModel = nil;
    if (indexPath.section < self.dataArr.count) {
        ordermOrderModel = self.dataArr[indexPath.section];
    }
#pragma mark - 订单详情跳转页
    if (ordermOrderModel.orderType == 1) {
        YQGoodsOrderDetailsVC *detailsVC = [YQGoodsOrderDetailsVC new];
        detailsVC.OrderModel = ordermOrderModel;
        kYQPUSH(detailsVC);
    }else if (ordermOrderModel.orderType == 2) {
        YQGoodsHotelOrderDetailsVC *hotelOrderVC = [YQGoodsHotelOrderDetailsVC new];
        hotelOrderVC.type = 2;
        hotelOrderVC.orderId = ordermOrderModel.orderId;
        hotelOrderVC.orderModel = ordermOrderModel;
        kYQPUSH(hotelOrderVC);
    }else if (ordermOrderModel.orderType == 3){
        YQGoodsScenicspotOrderDetailsVC * scenicspotOrderVC = [YQGoodsScenicspotOrderDetailsVC new];
        scenicspotOrderVC.type = 3;
        scenicspotOrderVC.orderId = ordermOrderModel.orderId;
        scenicspotOrderVC.orderModel = ordermOrderModel;
        kYQPUSH(scenicspotOrderVC);
    }else{
        YQGoodsActionOrderDetailsVC * actionOrderVC = [YQGoodsActionOrderDetailsVC new];
        actionOrderVC.type = 4;
        actionOrderVC.orderId = ordermOrderModel.orderId;
        actionOrderVC.orderModel = ordermOrderModel;
        kYQPUSH(actionOrderVC);
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end

#pragma makr -- YQOrderManageBtnActionCellDelegate
-(void)orderSateBtnActionSelected:(NSIndexPath *)indexPath :(NSInteger)index {
    YQGoodsOrderModel *orderOrderModel = nil;
    if (indexPath.section < self.dataArr.count) {
        orderOrderModel = self.dataArr[indexPath.section];
    }
    
    switch (orderOrderModel.orderStatus) {
        case 101:
        {
            if (index == 0) {
                QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:kYQLS(@"确定取消该订单?") message:@"" preferredStyle:(QMUIAlertControllerStyleAlert)];
                
                [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"我再想一想") style:(QMUIAlertActionStyleCancel) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                    
                }]];
                alert.alertCancelButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:UIFontBoldMake(17),NSKernAttributeName:@(0)};
                
                [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"确定") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                    //取消订单
                    [self cancelActionOrderModel:orderOrderModel];
                }]];
                alert.alertButtonAttributes = @{NSForegroundColorAttributeName:HexColor(0xB7B7B7),NSFontAttributeName:kSystemMedium(17),NSKernAttributeName:@(0)};
                
                [alert showWithAnimated:YES];

            }else{
                //立即支付
                [MYShopSalesOrderPayView shopSalesOrderPayView:[NSString stringWithFormat:@"%.2lf",orderOrderModel.totalMoney] :^(NSInteger index, NSString * typeStr) {
                    
                    [self getOrderPayType:index orderId:orderOrderModel.orderId orderType:[NSString stringWithFormat:@"%zd",orderOrderModel.orderType]];
                } :^{
                    NSLog(@"");
                }];
            }
        }
            break;
        case 102:
        case 103:
        case 202:
            //重新下单
        {
            //订单类型：1->普通商品订单；2->酒店订单；3->景点订单；4->课程订单
            
            if (orderOrderModel.orderType == 1) {
                NSMutableArray *goodsArr = @[].mutableCopy;
                for (YQGoodsOrderItemModel *itemModel in orderOrderModel.orderItemList) {
                    
                    YQPCartModel *cartModel = [YQPCartModel new];
                    cartModel.skuId = itemModel.skuId;
                    cartModel.itemNumber = [NSString stringWithFormat:@"%zd",itemModel.goodsNum];;
                    cartModel.skuImg = itemModel.goodsImg;
                    cartModel.specification = itemModel.specification;
                    cartModel.price = [NSString stringWithFormat:@"%.2lf",itemModel.goodsPrice];
                    cartModel.skuName = itemModel.goodsName;
                    cartModel.freight = @"";//暂无邮费
                    [goodsArr addObject:cartModel];
                }
                
                MYShopSalesOrderVC *orderVC = [[MYShopSalesOrderVC alloc] init];
                orderVC.selectGoodArray = goodsArr.copy;
                [self.navigationController pushViewController:orderVC animated:true];
            }else if(orderOrderModel.orderType == 2){
                YQGoodsOrderItemModel *itemModel = orderOrderModel.orderItemList.firstObject;
                MYNewsShopDetailsHotelVC *hotelVC = [MYNewsShopDetailsHotelVC new];
                hotelVC.type = 0;
                hotelVC.informationId = itemModel.skuId;
                hotelVC.isProduct = YES;
                kYQPUSH(hotelVC);
            }else if(orderOrderModel.orderType == 3){
                YQGoodsOrderItemModel *itemModel = orderOrderModel.orderItemList.firstObject;
                MYNewsShopDetailsScenicspotVC *hotelVC = [MYNewsShopDetailsScenicspotVC new];
                hotelVC.type = 1;
                hotelVC.informationId = itemModel.skuId;
                hotelVC.isProduct = YES;
                kYQPUSH(hotelVC);
            }else{
                YQGoodsOrderItemModel *itemModel = orderOrderModel.orderItemList.firstObject;
                MYNewsShopDetailsActionVC *hotelVC = [MYNewsShopDetailsActionVC new];
                hotelVC.type = 2;
                hotelVC.informationId = itemModel.skuId;
                hotelVC.isProduct = YES;
                kYQPUSH(hotelVC);
            }
        }
            break;
        case 201:
            
            break;
            
        case 301:
            if (index == 0) {
                //查看物流
//                kMBMesHUD(kYQLS(@"暂未开放"));
                YQGoodsOrderModel *itemModel = orderOrderModel;

                YQPOrderLogicsViewController *writeVC = [[YQPOrderLogicsViewController alloc] init];
                writeVC.orderId = itemModel.orderId;
                [self.navigationController pushViewController:writeVC animated:true];
            }else{
                //确认收货
                [self receiveGoodsOrderModel:orderOrderModel];
            }
            break;
        case 302:
        case 303:
            //发布评论
        {
            if (orderOrderModel.commentType == 0) {
                if ([orderOrderModel.comment isEqualToString:@"0"]) {
                    OrderEvaViewController *VC = [[OrderEvaViewController alloc] init];
                    VC.orderModel = orderOrderModel;
                    [self.navigationController pushViewController:VC animated:true];
                }else{
                    YQQueryOrderEvaViewController *VC = [[YQQueryOrderEvaViewController alloc] init];
                   VC.orderModel = orderOrderModel;
                   [self.navigationController pushViewController:VC animated:true];
                }
                
            }else{
                MBSucHUD(kYQLS(@"评价已过期"))
            }
        }
            break;
        default:
            break;
    }
    
}

#pragma makr -- YQOrderManageBtnActionCellDelegate end
///确认收货
-(void)receiveGoodsOrderModel:(YQGoodsOrderModel *)orderModel {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"orderId"] = orderModel.orderId;
    parameters[@"orderType"] = @(orderModel.orderType);
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendPostRequest:kPOST_RECEIVE_GOODS_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            orderModel.orderStatus = 302;
            [self getOrderList];
            YQUITIPSSUCCEED(responseObject.msg)
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
    }];
}

-(void)cancelActionOrderModel:(YQGoodsOrderModel *)orderModel {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"cancelOrderContent"] = @"";
    parameters[@"orderId"] = orderModel.orderId;
    parameters[@"orderType"] = @(orderModel.orderType);
    YQSHOWLOADINGINVIEW;
    [YQPNetWorkingManager sendPostRequest:kPOST_GOODS_ORDER_cancel_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            orderModel.orderStatus = 102;
            [self getOrderList];
            YQUITIPSSUCCEED(responseObject.msg)
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
        
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
    }];
}

-(void)getOrderPayType:(NSInteger)type orderId:(NSString *)orderId orderType:(NSString *)orderType {
    NSMutableDictionary *par = @{}.mutableCopy;
    par[@"orderId"] = orderId;
    par[@"payType"] = @(type + 1);
    par[@"orderType"] = orderType;
    self.payParameters=par;
    NSString *url=kALIPAY_ALIPAYPAYREQUEST_URL;
       if (type==1)
       {
           url=kALIPAY_WECHATPAYPAYREQUEST_URL;
       }
    [YQPNetWorkingManager sendPostRequest:url parameters:par success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
           if (type == 0) {
                [self goToAlipayData:responseObject.data];
            }
            else
            {
                NSDictionary *dict=(NSDictionary*)responseObject.data;
                PayReq* req= [[PayReq alloc] init];
                req.openID=[dict objectForKey:@"appId"];
                req.partnerId= [dict objectForKey:@"partnerId"];
                req.prepayId= [dict objectForKey:@"prepayId"];
                req.nonceStr = [dict objectForKey:@"nonceStr"];
                req.timeStamp= [[dict objectForKey:@"timestamp"] intValue];
                req.package= [dict objectForKey:@"packageStr"];
                req.sign= [dict objectForKey:@"sign"];
                [WXApi sendReq:req completion:^(BOOL success) {
                    NSLog(@"1");
                }];
            }
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
    }];
}
-(void)goToAlipayData:(NSString *)dataStr{
    NSString *appScheme = @"com.MuYing.www";
    [[AlipaySDK defaultService] payOrder:dataStr fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        //网页支付回调
        NSNotificationCenter *notiCenter=[NSNotificationCenter defaultCenter];
        //NSLog(@"result = %@",resultDic);
        NSString *resultStatus = resultDic[@"resultStatus"];
        if ([resultDic[@"memo"] isEqualToString:@""] && [resultStatus isEqualToString:@"9000"]) {
            /*支付成功通知*/
            [notiCenter postNotificationName:YJPaySucceedNotiKey object:self userInfo:nil];
        }else{
            
            if ([resultStatus isEqualToString:@"6001"]) {
                /*用户取消了支付*/
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    MBErrHUD(kYQLS(@"支付已取消"));
                });
            }else{
                NSString * strMsg = [NSString stringWithFormat:@"%@：%@,%@",kYQLS(@"支付结果"),kYQLS(@"支付失败"),resultDic[@"memo"]];
                NSLog(@"strMsg: %@",strMsg);
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
            
        }
    }];
}

-(void)paySucceedAction
{
   YQSHOWLOADINGINVIEW
   self.timer=[NSTimer scheduledTimerWithTimeInterval:2  target:self  selector:@selector(verifyPaymentResults) userInfo:nil  repeats:YES];
}

- (void)verifyPaymentResults
{
    [YQPNetWorkingManager sendPostRequest:kPAYRETURN parameters:self.payParameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            YQHIDELOADINGTIPS
            [self.timer invalidate];
            self.timer=nil;
            MYShopSalesOrderSucceedVC *succeedVC = [[MYShopSalesOrderSucceedVC alloc]initWithNibName:@"MYShopSalesOrderSucceedVC" bundle:nil];
            succeedVC.isIntegral = NO;
            succeedVC.navigationItem.title = kYQLS(@"支付成功");
            succeedVC.paySuceedLb.text = kYQLS(@"订单支付成功");
            succeedVC.paySuceedBtnText = kYQLS(@"查看我的订单");
            [self.navigationController pushViewController:succeedVC animated:true];
        }
        else if (responseObject.code==4) {
        }
        else
        {
                YQHIDELOADINGTIPS
                [self.timer invalidate];
                self.timer=nil;
                YQUITIPSERROR(responseObject.msg);
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
//        YQUITIPSERROR(error)
        [self.timer invalidate];
        self.timer=nil;
    }];
}
@end
